package cn.bisoft.java.util.os;

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;

public class ClipboardUtil
{
	private static Clipboard SYSTEM_CLIPBOARD = Toolkit.getDefaultToolkit().getSystemClipboard();

	// 1. 从指定的剪切板中获取文本内容
	public static String getText() throws Exception
	{
		// 获取剪切板中的内容
		Transferable clipT = SYSTEM_CLIPBOARD.getContents(null);

		if (clipT != null)
		{
			// 检查内容是否是文本类型
			if (clipT.isDataFlavorSupported(DataFlavor.stringFlavor))
			{
				return (String) clipT.getTransferData(DataFlavor.stringFlavor);
			}
		}
		
		return null;
	}

	// 2. 往剪切板写文本数据
	public static void setText(Clipboard clip, String text)
	{
		Transferable tText = new StringSelection(text);

		clip.setContents(tText, null);
	}

	// 3. 从剪切板读取图像
	public static Image getImage() throws Exception
	{
		Transferable cc = SYSTEM_CLIPBOARD.getContents(null);

		if (cc == null)
		{
			return null;
		}
		else if (cc.isDataFlavorSupported(DataFlavor.imageFlavor))
		{
			return (Image) cc.getTransferData(DataFlavor.imageFlavor);
		}
		return null;
	}

	// 4. 写图像到剪切板
	public static void setImage(final Image image)
	{
		Transferable trans = new Transferable()
		{
			public DataFlavor[] getTransferDataFlavors()
			{
				return new DataFlavor[] { DataFlavor.imageFlavor };
			}

			public boolean isDataFlavorSupported(DataFlavor flavor)
			{
				return DataFlavor.imageFlavor.equals(flavor);
			}

			public Object getTransferData(DataFlavor flavor)
			{
				if (isDataFlavorSupported(flavor))
				{
					return image;
				}

				return null;
			}
		};

		Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans, null);
	}
}
